#include "GLTexture.h"
#include "GLTextureManager.h"

namespace Myway {

	GLTexture::GLTexture()
		: mGLTexture(0)
		, mLockData(0)
	{
	}

	GLTexture::~GLTexture()
	{
		d_assert (mLockData == NULL);
		glDeleteTextures(1, &mGLTexture);
	}

	void GLTexture::Release()
	{
		d_assert (mReferenceCount == 0);

		((GLTextureManager *)TextureManager::Instance())->DestroyTexture(this);
	}

	void GLTexture::Lock(LockedRect * pLockedBox, int LockFlags)
	{
		d_assert (mLockData == NULL);

		mLockData = (void *) new unsigned char[4 * mWidth * mHeight];

		glBindTexture(GL_TEXTURE_2D, mGLTexture);
		glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, mLockData);

		pLockedBox->pData = mLockData;
		pLockedBox->Pitch = mWidth * 4;
	}

	void GLTexture::Unlock()
	{
		d_assert (mLockData != NULL);

		glBindTexture(GL_TEXTURE_2D, mGLTexture);
		glTexImage2D(GL_TEXTURE_2D, 0, 4, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mLockData);

		delete mLockData;
		mLockData = NULL;
	}

}